import React, { useState } from 'react';
import DebounceSelect from './DebounceSelect';
import userApi from '../../api/userApi';

interface UserValue {
  label: string;
  value: string;
  key?: string;
};

type UserSelectProps = {
  selectId?: string | undefined;
  value?: UserValue[] | null | undefined;
  style?: React.CSSProperties;
  onChange?: (value: UserValue[] | null | undefined) => void;
};

async function fetchUserList(keyword: string): Promise<UserValue[]> {
  const res: any = await userApi.query(keyword, '', '', '', '', 0, 100);
  const list: any[] = res.data?.list || [];
  return list.map((user: any) => ({
    value: user.id,
    label: user.name ? `${user.username}（${user.name}）` : user.username,
  }));
};

const UserSelect: React.FC<UserSelectProps> = ({ selectId, value, style, onChange }) => {
  const currentSelectedValue = (value && value.length) ? value[0].value : undefined;
  const [selectedValue, setSelectedValue] = useState<string | null | undefined>(undefined);
  const triggerChange = (changedValue: UserValue[] | null | undefined) => {
    onChange?.(changedValue);
  };
  return (
    <DebounceSelect
      id={selectId}
      selectedValue={selectedValue === undefined ? currentSelectedValue : selectedValue}
      placeholder="选择用户"
      fetchOptions={fetchUserList}
      onChange={(newValue) => {
        const value = newValue as UserValue[];
        setSelectedValue(value?.length ? value[0].value : null);
        triggerChange(value);
      }}
      style={style}
    />
  );
};

export default UserSelect;
